package cn.sxt.topic;

import lombok.SneakyThrows;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/6/10 15:08
 */
public class TestTopicConsumer {
    //地址在mq conf activemq.xml里面找
    private static final String BROKER_URL = "tcp://39.99.166.61:61616";
    private static final String TOPIC_NAME = "mq-topic-test";

    public static void main(String[] args) throws JMSException, IOException {
        ConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL);

        Connection connection = factory.createConnection();

        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        Topic topic = session.createTopic(TOPIC_NAME);

        MessageConsumer consumer = session.createConsumer(topic);
        System.out.println("Topic-1--消费者开始消费。。。");

        consumer.setMessageListener(new MessageListener() {
            @SneakyThrows
            @Override
            public void onMessage(Message message) {
                if (message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message;
                    System.out.println("Topic接收到消息：" +textMessage.getText());
                }
            }
        });
        System.in.read();

        connection.close();
        consumer.close();
        session.close();


    }
}
